import json
import requests
from typing import Dict, Any

from config import API_STRATEGIES_all
from Postgre_API.data_process import sql_result_processor

# api地址
boat_url = 'http://10.1.161.53:5000/api/boat'
portflow_url = 'http://10.1.161.53:5000/api/portflow'
boatName_url = 'http://10.1.161.53:5000/api/boatName'
warning_url = 'http://10.1.161.53:5000/api/warning'
channelName_url = 'http://10.1.161.53:5000/api/space/channel'
boatChannel_url = 'http://10.1.161.53:5000/api/space/boat'

def call_api(request_params: Dict[str, Any]) -> Dict[str, Any]:

    global cleaned_rows, payload
    cleaned_rows = []
    api_type = request_params.get('api')
    parameters = request_params.get('parameters', {})

    # 合法api名
    if not api_type or api_type not in API_STRATEGIES_all:
        raise ValueError(f"未定义的API类型: {api_type}")

    try:
        # 监控船只经过卡口（检查点）的情况
        if api_type in ["checkpoint_passage"]:

            # 定义字段名映射关系
            field_mapping = {
                "BOATNAME": "船名",
                "PASSTIME": "过船时间",
                "PORT": "卡口名称",
                "BOATTYPE": "船舶类型",
                "DIRECTION": "航向",
                "WARNTYPE": "预警类型",
                "WARNTIME": "预警时间"
            }

            payload = {
                "boatName": parameters.get("boatName"),
                "startTime": parameters.get("startTime"),
                "endTime": parameters.get("endTime")
            }

            headers = {'Content-Type': 'application/json'}
            response = requests.post(boat_url, data=json.dumps(payload), headers=headers)
            response_result = response.json()
            print("数据库查询成功")
            print(response_result)

            # 数据处理
            for row in response_result.get("result", []):
                # 先清理不需要的字段
                cleaned_row = {
                    k: v for k, v in row.items()
                    if k not in ["CODE", "HEIGHT", "LENGTH", "WIDTH", "LOAD", "SPEED"]
                }
                # 替换字段名为中文
                translated_row = {
                    field_mapping.get(k, k): v  # 如果字段不在映射中则保留原名
                    for k, v in cleaned_row.items()
                }
                cleaned_rows.append(translated_row)
            print("获取到的数据字段清理替换成功")
            print(cleaned_rows)

        # 预警相关（船舶在哪个卡口哪个时间有哪个预警）
        elif api_type in ["violation_detection"]:

            # 定义字段映射关系
            field_mapping = {
                "warntime": "预警时间",
                "boatname": "船名",
                "warntype": "预警类型",
                "passtime": "过船时间",
                "bayonetname": "卡口名称"
            }

            payload = {
                "boatName": parameters.get("boatName"),
                "startTime": parameters.get("startTime"),
                "endTime": parameters.get("endTime")
            }

            headers = {'Content-Type': 'application/json'}
            response = requests.post(warning_url, data=json.dumps(payload), headers=headers)
            response_result = response.json()
            print("数据库查询成功")
            print(response_result)

            # 数据处理
            for row in response_result.get("result", []):
                # 先清理不需要的字段
                cleaned_row = {
                    k: v for k, v in row.items()
                    if k not in ["warncode", "photoname", "photoposition", "msgsendstatus", "bayonetid"]
                }
                # 替换字段名为中文
                translated_row = {
                    field_mapping.get(k, k): v  # 如果字段不在映射中则保留原名
                    for k, v in cleaned_row.items()
                }
                cleaned_rows.append(translated_row)
            print("获取到的数据字段清理替换成功")
            print(cleaned_rows)

        # 查询特定卡口通过的船舶信息
        elif api_type in ["checkpoint_traffic"]:

            field_mapping = {
                'BAYONETNAME': '卡口名称',
                'PASS_DATE': '过船日期',
                'TOTAL': '流量',
                'OUTCOUNT': '出沪流量',
                'INCOUNT': '入沪流量',
                'DRYSHIP': '干货船流量',
                'OILSHIP': '油船流量',
                'BULKSHIP': '散货船流量',
                'BULKCHEMICALSHIP': '散装化学品船流量',
                'BULKCEMENTSHIP': '散装水泥运输船流量',
                'MULTIPURPOSESHIP': '多用途船流量',
                'OTHER': '其他类型船流量',
                'ZD': '总吨数'
            }

            payload = {
                "bayonet_name": parameters.get("checkpointName"),
                "startTime": parameters.get("startTime"),
                "endTime": parameters.get("endTime")
            }

            headers = {'Content-Type': 'application/json'}
            response = requests.post(portflow_url, data=json.dumps(payload), headers=headers)
            response_result = response.json()
            print("数据库查询成功")
            print(response_result)

            # fields = {
            #     "incount_all": response_result.get("incount_all"),
            #     "outcount_all": response_result.get("outcount_all"),
            #     "total_all": response_result.get("total_all")
            # }

            # 数据处理
            # for row in response_result.get("result", []):
            #     # 直接替换字段名为中文，未指定的字段保留原名
            #     translated_row = {
            #         field_mapping.get(k, k): v
            #         for k, v in row.items()
            #     }
            #     cleaned_rows.append(translated_row)
                # cleaned_rows.append(fields)

            result = response_result.get("result")
            cleaned_rows = sql_result_processor(result)
            print("获取到的数据字段清理替换成功")
            print(cleaned_rows)

            # 转换成markdown形式
            # 提取列名（按 field_mapping 的顺序）
            # columns = list(field_mapping.values())
            # # 构建 Markdown 表格
            # markdown_table = []
            # # 添加表头
            # markdown_table.append('|' + '|'.join(columns) + '|')
            # # 添加分隔行
            # markdown_table.append('|' + '|'.join(['---'] * len(columns)) + '|')
            # # 添加数据行
            # for row in cleanedRows:
            #     row_data = [str(row.get(col, '')) for col in columns]
            #     markdown_table.append('|' + '|'.join(row_data) + '|')
            # # 合并为完整的 Markdown 表格字符串
            # cleaned_rows = '\n'.join(markdown_table)
            # # 打印或输出结果
            # print("markdown结果：")
            # print(cleaned_rows)

        # 获取船只的基本信息
        elif api_type == 'basic_information':

            field_mapping = {
                'boatname': '船舶名称',
                "mmsi": "mmsi",
                "regno": "船舶登记号",
                "portname": "船籍港名称",
                "shipregiontype": "海船/内河船",
                "shiptypename": "船舶种类",
                "shiplength": "船舶长度",
                "shipwidth": "船舶型宽",
                "shipdepth": "船舶型深",
                "owner": "船舶所有人",
                "buildtime": "建造日期",
                "power": "主机总功率",
                "zd": "总吨位"
            }

            payload = {
                "boatName": parameters.get("boatName")
            }

            headers = {'Content-Type': 'application/json'}
            response = requests.post(boatName_url, data=json.dumps(payload), headers=headers)
            response_result = response.json()
            print("数据库查询成功")
            print(response_result)

            # 数据处理
            result_data = response_result.get("result", {})
            translated_row = {field_mapping.get(k, k): v for k, v in result_data.items()}
            cleaned_rows.append(translated_row)
            print("获取到的数据字段清理替换成功")
            print(cleaned_rows)

        # 空间计算相关（查询特定航道的船舶情况）
        elif api_type in ["spatial_computing_channel"]:

            # 定义字段映射关系
            field_mapping = {
                "total_count": "船舶总数量",
                "ship_type_count": "各类型船舶数量",
                "specific_types_count": "危险品船舶总数量"
            }

            payload = {
                "waterwayName": parameters.get("waterwayName"),
                "startTime": parameters.get("startTime"),
                "endTime": parameters.get("endTime")
            }

            headers = {'Content-Type': 'application/json'}
            response = requests.post(channelName_url, data=json.dumps(payload), headers=headers)
            response_result = response.json()
            print("数据库查询成功")
            print(response_result)

            # 遍历原始数据的顶层字段
            for key, value in response_result.items():
                # 跳过不需要的字段
                if key in ["result", "crossed_ships"]:
                    continue

                # 替换字段名为中文
                translated_key = field_mapping.get(key, key)

                # 添加到列表中
                cleaned_rows.append({
                    "字段名": translated_key,
                    "值": value
                })

            # 输出处理后的结果
            print("处理后的数据字段替换成功")
            print(cleaned_rows)

        # 空间计算相关（查询某条船经过航道的情况）
        elif api_type in ["spatial_computing_boat"]:

            # 定义字段映射关系
            field_mapping = {
                "crossed_channels": "航道"
            }

            payload = {
                "boatName": parameters.get("boatName"),
                "startTime": parameters.get("startTime"),
                "endTime": parameters.get("endTime")
            }

            headers = {'Content-Type': 'application/json'}
            response = requests.post(boatChannel_url, data=json.dumps(payload), headers=headers)
            response_result = response.json()
            print("数据库查询成功")
            print(response_result)

            # 遍历原始数据的顶层字段
            for key, value in response_result.items():
                # 跳过不需要的字段
                if key in ["result"]:
                    continue

                # 替换字段名为中文
                translated_key = field_mapping.get(key, key)

                # 添加到列表中
                cleaned_rows.append({
                    "字段名": translated_key,
                    "值": value
                })

            # 输出处理后的结果
            print("处理后的数据字段替换成功")
            print(cleaned_rows)

        # not matched 或者其它情况
        else:
            payload = parameters

        result = {
            "api": api_type,
            "payload": payload,
            "data": cleaned_rows
        }
        return result

    except requests.exceptions.RequestException as e:
        print(f"API调用失败（{api_type}）: {str(e)}")
        raise


# 使用示例（使用用户提供的参数）
# if __name__ == "__main__":
#     request_params = {
#         "api": "spatial_computing_boat",
#         "parameters": {
#             "boatName": "六安008",
#             "startTime": "2025-06-15 00:00:00",
#             "endTime": "2025-06-18 23:59:59",
#             "checkpointName": None,
#             "waterwayName": None
#         }
#     }
#
#     try:
#         result = call_api(request_params)
#         data = result.get('data')
#         print("API返回结果:", result)
#     except Exception as e:
#         print("处理失败:", e)